import React, { useRef, useState, useEffect } from 'react';
import { queryUpload } from '@/services/common';
import { Message } from '@/design';
import { getUmePic, isEmpty } from '@/utils/common';
import styles from './UploadImage.less';

export default function (props:any) {

  let unmount = false;

  const { className, max = 5, disabled, onChange, defaultValue = '' } = props;

  const uploadRef = useRef(null);

  const [files, setFiles] = useState<any>([]);
  const [viewPic, setViewPic] = useState('');


  /* 上傳圖片 */
  const handleFileChange = async (event:any) => {
    console.log('event.target.files', event.target.files, isEmpty(event.target.files))
    if (isEmpty(event.target.files)) return;
    let msg = '';
    let file = event.target.files[0];
    /* 判斷大小 */
    // if (file.size > 1 * 1024 * 1024) {
    //   msg = '圖片大小請控制在 1MB 以內！'
    // };
    /* 判斷是否已上傳（依據為：名稱和大小是否同時相同） */
    files.forEach((item:any) => {
      if (item.name === file.name && item.size === file.size) {
        msg = '此圖片已上傳';
      }
    })
    console.log(msg)
    if (!isEmpty(msg)) {
      console.log(msg)
      Message.error(msg);
      return;
    }
    /* 生成formdata */
    let formDt = new FormData();
    formDt.append("file", file);
    let result = await queryUpload(formDt);
    if (unmount || !result) return;
    // console.log(result)
    /* 上傳成功儲存結果 */
    setFiles([
      ...files,
      {
        name: file.name,
        size: file.size,
        ename: result.data
      }
    ])
  }

  /* 刪除圖片 */
  const deleteFile = (index:any) => {
    let newFiles = JSON.parse(JSON.stringify(files));
    newFiles.splice(index, 1);
    setFiles(newFiles);
  }

  useEffect(() => {
    if (onChange) {
      let picNames:any = [];
      files.forEach((item:any) => {
        picNames.push(item.ename);
      })
      onChange(picNames.join(','));
    }
  }, [files])

  /* 復現 */
  useEffect(() => {
    if (!isEmpty(defaultValue)) {
      let picNames = defaultValue.split(',');
      let newFiles:any = [];
      picNames.forEach((item:any) => {
        if (!isEmpty(item)) {
          newFiles.push({
            name: undefined,
            size: undefined,
            ename: item
          });
        }
      })
      setFiles(newFiles);
    }
  }, [props.defaultValue])

  useEffect(() => {
    return () => {
      unmount = true
    }
  }, [])

  return <div className={`${styles.upload_wrap} ${className || ''}`}>
    {!isEmpty(files) && <div className={styles.upload_list}>
      {files.map((item:any, index: number) => (
        <div key={item.ename} className={styles.upload_item}>
          {!disabled && <i onClick={()=>{deleteFile(index)}}></i>}
          <img src={getUmePic(item.ename)} alt="" onClick={() => { setViewPic(item.ename) }}/>
        </div>
      ))}
    </div>}
    <div className={`${styles.img_view} ${!isEmpty(viewPic) && styles.active}`} onClick={() => { setViewPic('') }}><img src={viewPic} /></div>
    {!disabled && files.length < max && <div className={styles.upload_button}>
      上傳圖片
      <input ref={uploadRef} type="file" accept="image/*" onChange={handleFileChange} />
    </div>}
  </div>
}